package com.ssish.saas.eccs.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ssish.saas.eccs.dto.BenefitChargeDto;
import com.ssish.saas.eccs.dto.MedicialDto;
import com.ssish.saas.eccs.mapper.ClaimsVoMapper;
import com.ssish.saas.eccs.mapper.SymUsrcoMapper;
import com.ssish.saas.eccs.model.SymUser;
import com.ssish.saas.eccs.model.SymUsrco;
import com.ssish.saas.eccs.model.SymUsrcoExample;
import com.ssish.saas.eccs.util.BeanHelper;
import com.ssish.saas.eccs.util.EncryptUtil;
import com.ssish.saas.eccs.util.HttpClientUtil;
import com.ssish.saas.eccs.vo.MedicialRecordVo;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class MedicialService {
    @Autowired
    private ClaimsVoMapper claimsVoMapper;
    @Autowired
    private SymUsrcoMapper symUsrcoMapper;
    @Value("${eccs.provider.userid}")
    private String userId;
    @Value("${eccs.proficer.password}")
    private String password;
    @Value("${eccs.benefit.url}")
    private String benefitUrl;

    /**
     * 就诊列表的信息
     * @param medicialDto
     * @return
     * @throws Exception
     */
    public List<MedicialRecordVo> getMedicialInfo(MedicialDto medicialDto) throws Exception{
        List<MedicialRecordVo> medicialRecordVoList = claimsVoMapper.getMedicialRecordList(medicialDto);
        for(MedicialRecordVo medicialRecordVo : medicialRecordVoList){
            BeanHelper.nullToEmpty(medicialRecordVo);
        }
        return medicialRecordVoList;
    }

    /**
     * 就诊记录的详情信息
     * @param claimsId
     * @return
     */
    public Map<String,Object> getMedicialRecordDetail(String claimsId){
        Map<String,Object> resultMap = new HashMap<>();
        resultMap = claimsVoMapper.getMedicialRecordDetail(claimsId);
        for(Map.Entry<String, Object> entry : resultMap.entrySet()){
            String mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            if(mapValue == null){
                resultMap.put(mapKey,"");
            }
        }

        List<Map<String,Object>> beneList = claimsVoMapper.getBeneListRecord(claimsId);
        resultMap.put("beneList",beneList);
        BigDecimal incurredOrgTotal =BigDecimal.ZERO;//医院发生金额
        BigDecimal amtDiscountTotal =BigDecimal.ZERO;//折扣金额
        BigDecimal amtIncrrredTotal =BigDecimal.ZERO;//折后金额
        BigDecimal amtApprovedTotal =BigDecimal.ZERO;//赔付金额
        BigDecimal amtToPayTotal =BigDecimal.ZERO;//自负金额
        if(beneList != null && beneList.size()>0){
            for(Map<String,Object> beneMap:beneList){
                Object amtIncurrdOrg = beneMap.get("amtIncurrdOrg");
                if(amtIncurrdOrg == null || StringUtils.isBlank(amtIncurrdOrg.toString())){
                    amtIncurrdOrg ="0";
                }
                incurredOrgTotal = incurredOrgTotal.add(new BigDecimal((String)amtIncurrdOrg));
                Object amtDiscount = beneMap.get("amtDiscount");
                if(amtDiscount == null || StringUtils.isBlank(amtDiscount.toString())){
                    amtDiscount ="0";
                }
                amtDiscountTotal = amtDiscountTotal.add(new BigDecimal((String)amtDiscount));

                Object amtIncurred = beneMap.get("amtIncurred");
                if(amtIncurred == null || StringUtils.isBlank(amtIncurred.toString())){
                    amtIncurred ="0";
                }
                amtIncrrredTotal = amtIncrrredTotal.add(new BigDecimal((String)amtIncurred));

                Object amtApproved = beneMap.get("amtApproved");
                if(amtApproved == null || StringUtils.isBlank(amtApproved.toString())){
                    amtApproved ="0";
                }
                amtApprovedTotal = amtApprovedTotal.add(new BigDecimal((String)amtApproved));
                Object amtToPay = beneMap.get("amtToPay");
                if(amtToPay == null || StringUtils.isBlank(amtToPay.toString())){
                    amtToPay ="0";
                }
                amtToPayTotal = amtToPayTotal.add(new BigDecimal((String)amtToPay));
            }
        }
        resultMap.put("incurredOrgTotal",incurredOrgTotal);
        resultMap.put("amtDiscountTotal",amtDiscountTotal);
        resultMap.put("amtIncrrredTotal",amtIncrrredTotal);
        resultMap.put("amtApprovedTotal",amtApprovedTotal);
        resultMap.put("amtToPayTotal",amtToPayTotal);
        return resultMap;
    }

    /**
     * 获取常见疾病列表
     * @param providerCode
     * @param coverageCode
     * @param deptName
     * @return
     */
    public List<Map<String,Object>> getMedicialTypeList(String providerCode,String coverageCode, String deptName){
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("providerCode",providerCode);
        paramMap.put("deptName",deptName);
        paramMap.put("coverageCode",coverageCode);
        List<Map<String,Object>> returnMapList = claimsVoMapper.getMedicialTypeList(paramMap);
        if(returnMapList == null||returnMapList.size() ==0){
            paramMap.put("providerCode","ZZZ");
            returnMapList = claimsVoMapper.getMedicialTypeList(paramMap);
        }
        for(Map<String,Object> map:returnMapList){
            if(map.get("icdCode") == null){
                 map.put("icdCode","");
            }
            if(map.get("nickName") == null){
                map.put("nickName","");
            }
            if(map.get("deptName") == null){
                map.put("deptName","");
            }
        }
        return returnMapList;
    }

    /**
     * 获取pos机的terminalId，provider
     * @param user
     * @return
     */
    public Map<String,Object> getTerminalId(SymUser user){
        Map<String,Object> returnMap= new HashMap();
        String providerCode="";
        SymUsrcoExample symUsrcoExample = new SymUsrcoExample();
        symUsrcoExample.createCriteria().andUsridEqualTo(user.getUsrid());
        List<SymUsrco> symUsrcoList = symUsrcoMapper.selectByExample(symUsrcoExample);
        if(symUsrcoList!= null && symUsrcoList.size()>0){
            providerCode = symUsrcoList.get(0).getStncd();
        }
        returnMap.put("providerCode",providerCode);
        String terminalId = claimsVoMapper.getTerminalId(providerCode);
        returnMap.put("terminalId",terminalId);
        return returnMap;
    }
    /**
     * 获取门诊计算基础信息
     * @param claimsId
     * @return
     */
    public Map<String,Object> getChargeEmpDetail(String claimsId,SymUser user){
        Map<String,Object> charEmpMap = claimsVoMapper.getChargeEmpDetail(claimsId);
        charEmpMap.put("terminalId",getTerminalId(user));
        for(Map.Entry<String, Object> entry :charEmpMap.entrySet()){
            String mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            if(mapValue == null){
                charEmpMap.put(mapKey,"");
            }
        }
        String  deptName = claimsVoMapper.getStrative(claimsId);
        charEmpMap.put("deptName",StringUtils.isBlank(deptName)?"":deptName);
        return charEmpMap;
    }

    /**
     *  获取付费项目列表信息(调接口)
     * @param Terminalid
     * @param Card_no
     * @param Coverage_code
     * @param Admission_date
     * @return
     * @throws Exception
     */
    public Map<String,Object> getBenefitItemInfo(String Terminalid,String Card_no,String Coverage_code,String Admission_date) throws Exception{
        Map<String,String> parmMap=new HashMap<String,String>();
        Map<String,Object> returnMap = new HashMap<>();
        String times=(int) new Date().getTime()+"";
        String timeStr=times.substring(1,times.length());
        parmMap.put("Terminalid", Terminalid);
        parmMap.put("Admission_date", Admission_date);
        parmMap.put("Coverage_code", Coverage_code);
        parmMap.put("Card_no", Card_no);
        parmMap.put("UserId", userId);
        parmMap.put("Passwd", password);
        String json= "["+JSONObject.toJSONString(parmMap)+"]";
        String enjson= EncryptUtil.encrypt(json, "rZcXb3"+timeStr, timeStr+"123456");
        String paramData ="pstJson="+timeStr+"."+enjson;
        String res= HttpClientUtil.sendUserPost(benefitUrl,paramData);
        try {
            Document doc = DocumentHelper.parseText(res);
            Element root = doc.getRootElement();
            Element planCode = root.element("Plan_code");
            Element coverage = root.element("Coverage_code");
            Element BenefitList = root.element("BenefitList");
            if(planCode != null){
                returnMap.put("planCode",planCode.getTextTrim());
            }
            if(coverage != null){
                returnMap.put("coverage",coverage.getTextTrim());
            }
            if(BenefitList != null){
                List <BenefitChargeDto> benefitChargeDtoList = new ArrayList<>();
                String beneStr = BenefitList.getTextTrim();
                benefitChargeDtoList = JSONObject.parseArray(beneStr, BenefitChargeDto.class);
                returnMap.put("benefitList",benefitChargeDtoList);
            }
            return returnMap;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}
